/*
 * @Description: Description
 * @Author: Kerwin
 * @Date: 2025-06-23 10:12:40
 * @LastEditTime: 2025-06-23 10:12:55
 * @LastEditors:  Please set LastEditors
 */
/* eslint-disable no-plusplus */
/* eslint-disable no-unused-expressions */
/* eslint-disable @typescript-eslint/no-empty-function */
/* eslint-disable no-useless-constructor */
/*
 * @Description: Description
 * @Author: Kerwin
 * @Date: 2023-10-17 09:58:16
 * @LastEditTime: 2025-05-20 15:06:31
 * @LastEditors:  Please set LastEditors
 */

import { browserVersion, setCookie } from '@/utils/common'

class JSBridgeClass {
  constructor() {}

  id = 0

  callbacks = {}

  registerFuncs = {}

  nativeBridge = null

  invoke(eventName, data, callback) {
    const thisId = this.id++ // 获取唯一 id
    this.callbacks[thisId] = callback // 存储 Callback
    const ua = browserVersion()
    // 判断环境，获取不同的 nativeBridge
    if (ua.isAndroid) {
      this.nativeBridge = window.nativeBridge
      console.log('is andiord bridge', this.nativeBridge)
    }
    if (ua.isIos) {
      this.nativeBridge = window.webkit.messageHandlers.CallbackEvent // WKWebView
      console.log('is ios bridge', this.nativeBridge)
    }
    // this.registerEvent(data.bridgeName, callback)
    if (this.nativeBridge) {
      this.nativeBridge.postMessage({
        eventName,
        data: data || {}
      })
    }
  }

  registerEvent(bridgeName, callback) {
    this.registerFuncs[bridgeName] = callback
  }

  callbackEvent(msg) {
    console.log('callbackEvent===>', msg)
    if (!(msg instanceof Object)) {
      msg = JSON.parse(msg)
    }
    const { bridgeName } = msg
    const data = msg.data || {}
    console.log('callbackEvent===>', bridgeName)
    if (bridgeName) {
      this.registerFuncs[bridgeName] && this.registerFuncs[bridgeName](data)
    }
  }

  // new
  HYUserEvent(msg) {
    console.log('app原始jsBrige数据==>', msg)
    let newMsg, data
    if (!(msg instanceof Object)) {
      newMsg = msg.replace(/\s+/g, '')
      data = JSON.parse(newMsg)
    } else {
      data = msg
    }
 
    uni.setStorageSync('userInfo', data)
    console.log('JSBridge用户信息:', data)
    const token = data.token || data.auth // ios 和 andiord 给的key不一致
    if (token) {
      token.accessToken && setCookie('HYToken', token.accessToken)
      token.blmToken && setCookie('BLMToken', token.blmToken)
    }
 
    
  // ✅ 安全地处理定位信息
  try {
    console.log('app用户信息==>', msg.currentLocaiton?.mData)

    const lat = msg.currentLocaiton?.mData?.lat
    const lon = msg.currentLocaiton?.mData?.lon

    if (lat && lon) {
      const currentLocaiton = { latitude: lat, longitude: lon }
      uni.setStorageSync('userLocation', currentLocaiton)
      console.log('✅ 成功保存 App 定位:', currentLocaiton)
    } else {
      uni.setStorageSync('userLocation', {})
      console.warn('⚠️ App 传来的定位不完整，已设置空对象')
    }
  } catch (e) {
    console.error('❌ 定位解析失败:', e)
    uni.setStorageSync('userLocation', {})
    console.warn('兜底：清空 userLocation 缓存')
  }




    if (data.deviceSn) {
      setCookie('deviceSn', data.deviceSn)
      setCookie('serviceType', data.serviceType)
    }
    const bridgeName = 'HYUserEvent'
    let timer = setInterval(() => {
      if (this.registerFuncs[bridgeName]) {
        this.registerFuncs[bridgeName](data)
        clearInterval(timer)
        timer = null
      }
    }, 500)
  }
}
const JSBridge = new JSBridgeClass()

window.JSBridge = JSBridge
window.callbackEvent = JSBridge.callbackEvent.bind(JSBridge)
window.HYUserEvent = JSBridge.HYUserEvent.bind(JSBridge)
// 注册回调事件
/* window.JSBridge.registerEvent("bridgeName", (data) => {
  //  do something
}); 
*/
// 父项目是H5时需要监听message
window.addEventListener('message', (event) => {
  const { data } = event
  // console.log('bridge=>',data)
  if (data && data.userInfo) {
    window.HYUserEvent(data.userInfo)
  }
})

//  用于实现H5跟Ios交互的工具。
export const setupWebViewJavascriptBridge = (callback) => {
  if (window.WebViewJavascriptBridge) {
    return callback(window.WebViewJavascriptBridge)
  }
  if (window.WVJBCallbacks) {
    return window.WVJBCallbacks.push(callback)
  }
  window.WVJBCallbacks = [callback]
  const WVJBIframe = document.createElement('iframe')
  WVJBIframe.style.display = 'none'
  WVJBIframe.src = 'https://__bridge_loaded__'
  document.documentElement.appendChild(WVJBIframe)
  setTimeout(() => {
    document.documentElement.removeChild(WVJBIframe)
  }, 0)
}

export const callIosBridge = (IosMethodName, params, callback) => {
  setupWebViewJavascriptBridge((bridge) => {
    bridge.callHandler(IosMethodName, params, callback)
  })
}
